<?php

class DatabaseMysql extends Database {
	protected $link;
	
	public function __construct(array $opts) {
		$timer = microtime(1);
		
		$opts = array_merge(array(
			'host'    => null,
			'login'   => null,
			'pwd'     => null,
			'dbname'  => null,
			'charset' => null,
		), $opts);
		
		$this->link = mysql_connect($opts['host'], $opts['login'], $opts['pwd']);
		
		if ($opts['dbname'] !== null) {
			mysql_select_db($opts['dbname'], $this->link);
		}
		
		Log::write('Database connect: %2.5f', microtime(1)-$timer);
		
		if ($opts['charset'] !== null) {
			$this->query('SET NAMES '.$this->escape($opts['charset']));
		}
	}
	
	public function real_query($query) {
		$timer = microtime(1);
		$result = mysql_query($query, $this->link);
		Log::write("%s\n<b>Time</b>: %2.5f", $query, microtime(1)-$timer);
		if ($result === false) {
			throw new DatabaseException('Error in mysql query"%s": %s', $query, mysql_error());
		}
		return new DatabaseResult($this, $result);
	}
	
	public function fetch($result_resource) {
		return mysql_fetch_assoc($result_resource);
	}
	
	public function seek($result_resource, $row_number) {
		mysql_data_seek($result_resource, $row_number);
	}
	
	public function inserted() {
		return mysql_insert_id($this->link);
	}
	
	public function affected() {
		return mysql_affected_rows($this->link);
	}
	
	public function escape($string) {
		return mysql_real_escape_string($string, $this->link);
	}
}

